package spring.framework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import spring.framework.beans.BeansException;
import spring.framework.beans.factory.DisposableBean;
import spring.framework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @author fun.pengzh
 * @class spring.framework.beans.factory.support.DisposableBeanAdapter
 * @desc Bean的销毁适配器
 * @since 2021-10-10
 */
public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;
    private final String beanName;
    private final String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        //1、实现了DisposableBean接口
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        //2、配置了 DestoryMethod ，加判定为了防止再次销毁
        if (StrUtil.isNotBlank(destroyMethodName) && !("destroy".equals(destroyMethodName) && bean instanceof DisposableBean)) {
            Method method = bean.getClass().getMethod(destroyMethodName);
            if (method == null) {
                throw new BeansException("Couldn't find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'");
            }
            method.invoke(bean);
        }
    }
}
